/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package com.huawei.rpc.client.discovery;

import com.alibaba.fastjson.JSON;
import com.huawei.rpc.common.constants.CommonConstant;
import com.huawei.rpc.common.info.ServiceInfo;
import com.huawei.rpc.common.serializer.ZookeeperSerializer;
import org.I0Itec.zkclient.ZkClient;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author Lijl
 * @ClassName ZookeeperServiceDiscoverer
 * @Description 服务发现，定义以zookeeper为注册中心的服务发现
 * @Date 2022/2/14 16:00
 * @Version 1.0
 */
public class ZookeeperServiceDiscoverer implements IDiscovererService{

    private ZkClient zkClient;

    public ZookeeperServiceDiscoverer(String zkAddress){
        zkClient = new ZkClient(zkAddress);
        zkClient.setZkSerializer(new ZookeeperSerializer());
    }

    /**
     * @Author lijl
     * @MethodName getService
     * @Description 使用Zookeeper客户端，通过服务名获取服务列表
     * @Date 17:07 2022/3/11
     * @Version 1.0
     * @param name 服务名->接口全路径
     * @return: java.util.List<com.huawei.rpc.common.info.ServiceInfo> 服务列表
    **/
    @Override
    public List<ServiceInfo> getService(String name) {
        // /simple-rpc/接口全路径/service
        //从zk中获取已注册的服务
        String servicePath = CommonConstant.ZK_SERVICE_PATH+CommonConstant.PATH_DELIMITER+name+CommonConstant.PATH_DELIMITER+"service";
        List<String> children = zkClient.getChildren(servicePath);
        return Optional.ofNullable(children).orElse(new ArrayList<>()).stream().map(str -> {
            String deCh = null;
            try {
                deCh = URLDecoder.decode(str,CommonConstant.UTF_8);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return JSON.parseObject(deCh, ServiceInfo.class);
        }).collect(Collectors.toList());
    }
}
